package com.syqc.choose.car

import android.app.Activity
import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.ViewGroup.MarginLayoutParams
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.LinearLayoutManager
import autodispose2.autoDispose
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.syqc.comlib.base.LazyFragment
import com.syqc.comlib.rx.filterFast
import com.syqc.comlib.utils.hideSoftInput
import com.syqc.comlib.utils.loadStringDImgError
import com.syqc.comlib.utils.setResultTo
import com.syqc.comlib.utils.subPlate
import com.syqc.comlib.utils.toast
import com.syqc.entity.CarLick
import com.syqc.monitor.R
import com.syqc.monitor.databinding.FragmentSearchBinding
import com.syqc.monitor.databinding.IncludeSelectSureBinding
import com.syqc.monitor.databinding.PopupSearchTypeBinding
import com.syqc.utils.Keys
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers

/**
 *@Author Jasper
 *@Time   2020/7/22
 *@Desc   搜索车辆
 */
class SearchFragment(
    private val isVideo: Boolean = false,
    private val isChange: Boolean = false
) :
    LazyFragment<FragmentSearchBinding>(FragmentSearchBinding::inflate) {

    private lateinit var mSureVB: IncludeSelectSureBinding
    private var carInfo: CarLick? = null

    private val mViewModel: SearchViewModel by viewModels()
    private var typeStr = ArrayList<String>()
    private var hintStr = ArrayList<String>()
    private val mTypePopup by lazy {
        TypePopup(requireContext()) {
            mViewModel.type = it
            binding.tvChooseType.text = typeStr[it]
            binding.editPlate.hint = hintStr[it]
        }
    }


    override fun initView(view: View) {

        mSureVB = IncludeSelectSureBinding.bind(binding.root)
        hintStr.clear()
        hintStr.add(requireContext().getString(R.string.hint_search_car_plate))
        hintStr.add(requireContext().getString(R.string.hint_search_car_tmn))
        hintStr.add(requireContext().getString(R.string.hint_search_car_sim))
        hintStr.add(requireContext().getString(R.string.hint_search_car_logo))
        mSureVB.tvSure.setText(R.string.desc_com_sure)
        binding.llSearch.isVisible = true
        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(::toastObserver)
        binding.includeRecycler.recyclerView.layoutManager = LinearLayoutManager(context)
        binding.includeRecycler.recyclerView.adapter = SearchAdapter().apply {
            mViewModel.searchSub.autoDispose(scopeProvider).subscribe {
                if (isAdd) {
                    isAdd = false
                    setNewInstance(it)
                } else {
                    notifyDataSetChanged()
                }
                binding.llSearch.isVisible = it.size <= 0
            }

            setOnItemClickListener { adapter, view, position ->
                hideSoftInput()
                index = position
                notifyDataSetChanged()
                carInfo = data[position]
            }
        }
    }

    override fun initData() {
        mViewModel.wordsObserver().observeOn(AndroidSchedulers.mainThread())
            .autoDispose(scopeProvider).subscribe {
                initWords(it)
            }
        mViewModel.changeTeamLive.observe(this) {
            if (it == -1) {
                putCarInfo()
            } else {
                putCarInfo(it == 0)
            }
        }

        mViewModel.toastObserver().autoDispose(scopeProvider).subscribe(this::toastObserver)

        typeStr.clear()
        typeStr.add(getString(R.string.desc_car_plate_new))
        typeStr.add(getString(R.string.desc_tmn_num))
        typeStr.add(getString(R.string.desc_sim_num))
        typeStr.add(getString(R.string.desc_tmn_logo))
        mTypePopup.setData(typeStr)

    }

    private var isAdd = true
    override fun initEvent() {
        binding.tvSearchClear.filterFast {
            mViewModel.clear()
        }
        binding.tvSearch.filterFast {
            isAdd = true
            mViewModel.searchCars(binding.editPlate.text.toString(), isVideo)
        }

        mSureVB.tvSure.filterFast {
            if (carInfo == null) {
                context?.toast(R.string.toast_choose_one_car)
            } else {
                if (isChange) {
                    mViewModel.changeTeam(carInfo!!.carId)
                } else {
                    putCarInfo()
                }

            }
        }
        binding.tvChooseType.setOnClickListener {
            mTypePopup.show(binding.tvChooseType, mViewModel.type)
        }
    }

    private fun putCarInfo() {
        carInfo?.run {
            setResultTo(activity as Activity) {
                putExtra(Keys.INTENT_CAR_ID, carId)
                putExtra(Keys.INTENT_CAR_NAME, subPlate(carPlate, 14))
                putExtra(Keys.INTENT_TEAM_NAME, teamName)
                if (videos != null) putExtra(Keys.VIDEO, videos)
            }
            ChooseCars.addCars(
                carId = carId,
                carPlate = carPlate,
                carName = carName,
                videos = videos,
                iconLink = iconLink,
                isVideo = !videos.isNullOrEmpty()
            )
        }
        activity?.finish()
    }

    private fun putCarInfo(noAuth: Boolean) {
        carInfo?.run {
            setResultTo(activity as Activity) {
                putExtra(Keys.INTENT_CAR_ID, carId)
                putExtra(Keys.INTENT_CAR_NAME, subPlate(carPlate, 14))
                putExtra(Keys.INTENT_TEAM_NAME, teamName)
                putExtra(Keys.INTENT_NO_AUTH, noAuth.toString())
                if (videos != null) putExtra(Keys.VIDEO, videos)
            }
            ChooseCars.addCars(
                carId = carId,
                carPlate = carPlate,
                carName = carName,
                videos = videos,
                iconLink = iconLink,
                isVideo = !videos.isNullOrEmpty()
            )
        }
        activity?.finish()
    }


    private fun initWords(words: List<String>) {
        binding.cflSearch.removeAllViews()
        val lp = MarginLayoutParams(
            ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT
        )
        lp.leftMargin = 10
        lp.rightMargin = 10
        lp.topMargin = 3
        lp.bottomMargin = 3
        val length: Int = words.size
        for (i in 0 until length) {
            val str: String = words[i]
            val view = TextView(activity)
            view.text = str
            view.setTextColor(Color.BLACK)
            view.setBackgroundResource(R.drawable.bg_flow_optimal)
            view.setOnClickListener { v: View ->
                binding.editPlate.setText(str)
                binding.editPlate.setSelection(binding.editPlate.text.length)
                isAdd = true
                mViewModel.searchCars(str, isVideo)
            }
            binding.cflSearch.addView(view, lp)
        }
    }


    inner class SearchAdapter :
        BaseQuickAdapter<CarLick, BaseViewHolder>(R.layout.item_search_choose_car) {
        var index: Int = -1
        override fun convert(holder: BaseViewHolder, item: CarLick) {
            item.run {
                holder.run {
                    val check = getView<ImageView>(R.id.ivItemChoose)
                    check.isSelected = index == layoutPosition
                    getView<ImageView>(R.id.ivCarLogo).loadStringDImgError(context, iconLink)
                    setText(R.id.tvCarPlate, carPlate)
                    setText(R.id.tvCarName, carName)
                }
            }
        }
    }

}

class TypePopup(context: Context, callback: (index: Int) -> Unit) :
    PopupWindow() {
    private val popupBinding = PopupSearchTypeBinding.inflate(LayoutInflater.from(context))
    private val mAdapter by lazy { TypeChooseAdapter() }

    init {
        width = ViewGroup.LayoutParams.WRAP_CONTENT
        height = ViewGroup.LayoutParams.WRAP_CONTENT
        isOutsideTouchable = true
        isClippingEnabled = false //设置是否裁剪内容
        contentView = popupBinding.root
        setBackgroundDrawable(ColorDrawable(0xFFFFFFFF.toInt()))

        popupBinding.recyclerType.layoutManager = LinearLayoutManager(context)
        popupBinding.recyclerType.adapter = mAdapter
        mAdapter.setOnItemClickListener { adapter, view, position ->
            callback.invoke(position)
            dismiss()
        }
    }

    fun setData(data: ArrayList<String>) {
        mAdapter.setList(data)
    }

    fun show(view: View, index: Int) {
        mAdapter.index = index
        mAdapter.notifyDataSetChanged()
        showAsDropDown(view, Gravity.NO_GRAVITY, 0, 0)
    }
}

class TypeChooseAdapter : BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_choose_type) {
    var index = 0
    override fun convert(holder: BaseViewHolder, item: String) {
        holder.setText(R.id.tvChooseType, item)
        val tvChooseType = holder.getView<TextView>(R.id.tvChooseType)
        tvChooseType.text = item
        val isSelected = index == holder.layoutPosition
        tvChooseType.setBackgroundResource(if (isSelected) R.color.color_b5d else R.color.white)
    }
}